import {dealCache, messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { message, Form, Tag, Popover } from 'antd';
import menuRoute from 'routes/menuRoute'
import SearchArea from 'components/search-area'
import waitForBillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service';
import ExportModal from 'components/template/export-modal/export-modal';
import Condition from 'components/condition';
import moment from 'moment'
const vendorType=["DIDI","CLOUD_HELIOS_HOTEL","SHEN_ZHOU"];
import errorMessage from 'share/errorMessage'
import configureStore from "stores";
import {setBillList} from "actions/cache";
import {setBillingTab} from "actions/billing";
const If = Condition.If;
import ResizeTable from 'components/resize-table'

class WaitForBillingList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 0,
      size: 10,
      endDate: null,
      loading: false,
      data: [],
      billingType: props.billingType,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      searchParams: {},
      columns: [
        {title: messages('financial-management.key403'/*序号*/), dataIndex: 'index', width: 48},
        {title: messages('financial-management.key426'/*申请ID*/), dataIndex: 'applicantID', width: '12%'},
        {title: messages('financial-management.key433'/*开票类型*/), dataIndex: 'invoiceTypeResp', width: '15%',render:invoiceTypeResp => invoiceTypeResp?(<Popover content={invoiceTypeResp.name}>{invoiceTypeResp.name}</Popover>):""},
        {title: messages('my-account.key3'/*开票日期*/), dataIndex: 'createdDate',width:120, render: createdDate => new Date(createdDate).format('yyyy-MM-dd')},
        {title: messages('financial-management.key525'/*抬头信息*/), width: '15%',dataIndex: 'title',render:title =>(<Popover content={title}>{title}</Popover>)},
        {title: messages('financial-management.key405'/*币种*/), dataIndex: 'currency', width: 48},
        {title: messages('financial-management.key406'/*金额*/), dataIndex: 'amount',width: '9%',align: 'right', render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currency))},
        {title: messages('financial-management.key413'/*开票状态*/), dataIndex: 'status', render: (value,record) => {
            const { billingType } = this.state;
            let res = '';
            switch (value){
              case 'SUBMITTED':
                res = messages('financial-management.key526'/*处理中*/);
                break;
              case 'FAIL':
                res = messages('financial-management.key416'/*失败*/);
                break;
              case 'PARTSUCCESS':
                res = messages('financial-management.key527'/*部分成功*/);
                break;
              case 'REJECTED':
                res = messages('common.reject'/*驳回*/);
                break;
              default:
                res =messages('financial-management.key415')/*成功*/
                // res =  billingType === 'DIDI' ? <a onClick={e => this.handleViewDetail(e,record)}>{messages('financial-management.key415'/*成功*/)}</a> : messages('financial-management.key415'/*成功*/);
                break;
            }
            return res;
          }},
        {title: messages('financial-management.key528'/*备注*/), width: '15%', dataIndex: 'remark',render:this.renderRemark},
        {title: messages('common.operation'),dataIndex:'operate',render:this.renderOperate}
      ],
      buttonRoleSwitch:this.checkPageRole('RECEIPTEDINVOICES', 2),
      searchForm: [
        {
          type: 'items',
          id: 'dateRange',
          items: [
            {
              type: 'month',
              id: 'startDate',
              label: '请选择开票月份',
              defaultValue: moment().subtract(1, 'month')
            }, //开票起始日期
          ]
        },
        {
          type: 'select',
          id: 'title',
          label: messages('financial-management.key472'/*请选择抬头*/),
          options: []
        }
      ]
    };
    this.menuBillingDetail = menuRoute.getRouteItem('billing-detail');
  }

  componentWillMount(){
    let result = this.props.billList;
    if(result && JSON.stringify(result) !== "{}"){
      let { searchForm, page, searchParams } = this.state;
      page = result.page;
      result.startDate && (searchParams.startDate = moment(result.startDate).format('YYYY-MM-DD 00:00:00'));
      result.endDate && (searchParams.endDate = moment(result.endDate).format('YYYY-MM-DD 23:59:59'));
      result.title && (searchParams.title = result.title);
      dealCache(searchForm, JSON.parse(JSON.stringify(result)));
      this.setState({searchForm, page, searchParams},() => {
        this.getList();
        this.getInvoiceTitle();
        configureStore.store.dispatch(setBillList(null));
      })
    } else {
      this.getList(true);
      this.getInvoiceTitle();
    }
  }

  handleViewDetail = (e,record) => {
    e.stopPropagation();
    e.preventDefault();
    const { billingType } = this.state;
    this.props.dispatch(setBillingTab('done'));
    this.context.router.push(menuRoute.getRouteItem('invoice-status-query').url.replace(':billingType',billingType).replace(':companyOID',record.companyOID).replace(':receiptedInvoiceOID',record.receiptedInvoiceOID));
  };

  //渲染备注
  renderRemark = (value,record) =>{
    let content = record.remark ? record.remark : messages('financial-management.key529'/*无*/);
    return <Popover placement="topLeft" content={content}>{content}</Popover>;
  };

  //获得抬头信息
  getInvoiceTitle = () => {
    let { billingType } = this.state;
    let params = {
      companyOid:this.props.company.companyOID
    };
    waitForBillingService.getInvoiceTitle(billingType,params).then(res =>{
      if(res.data){
        res.data.unshift({id:'ALL',invoice_title:messages('common.all')});
        let options = [];
        res.data.map(item => {
          options.push({
            label: item.invoice_title,
            value: item.invoice_title,
            key: item.id
          });
        });
        let searchForm = this.state.searchForm;
        searchForm[1].options = options;
        this.setState({searchForm});
      }
    }).catch(e => {
      message.error(e.response.data.message);
    });
  };

  renderOperate = (value,record) =>{
    if(!this.checkNewAuth()){
      return <span/>
    }
    let fpObj = this.props.profile['vendor.receipt.config'] ? JSON.parse(this.props.profile['vendor.receipt.config'])['reject.repeat.order'] : false;
    if(this.props.profile['didi.invoice.check.enable'] && ~vendorType.indexOf(record.vendor) && record.confirmReceived === 0 && (record.status === 'SUCCESS' || fpObj)){
      return <a onClick={(e)=>this.confirmReceiptInvoice(e,record)}>{messages('financial-management.key532'/*确认收票*/)}</a>
    }
    if(this.props.profile['didi.invoice.check.enable'] &&  ~vendorType.indexOf(record.vendor) &&  record.status ==='SUCCESS' && record.confirmReceived === 1){
      return <Tag color="#A0D468">{messages('financial-management.key533'/*已收票*/)}</Tag>
    }
    if(record.statusId !== 1007 && record.statusId !== 1001){
      return <a onClick={(e)=>this.reApplyForReceiptedInvoice(e,record)}>{messages('financial-management.key441'/*重新开票*/)}</a>
    }
  };

  //重新开票
  reApplyForReceiptedInvoice = (e,record)=>{
    e.stopPropagation();
    waitForBillingService.reApplyForReceiptedInvoice(record.receiptedInvoiceOID).then(res =>{
      if(res.status === 200){
        message.success(messages('financial-management.key420'/*申请重新开票成功*/));
        this.getList()
      }
    }).catch((e)=>{
      errorMessage(e.response,messages('financial-management.key421'/*申请重新开票失败*/))
    })
  };

  //确认收票
  confirmReceiptInvoice = (e,record)=>{
    e.stopPropagation();
    waitForBillingService.receiptedInvoice(record.receiptedInvoiceOID).then(res=>{
      if(res.data.length > 0){
        res.data.map(item => {
          message.error(item.failReason);
        });
      }else{
        message.success(messages('financial-management.key534'/*确认收票成功*/));
      };
      this.getList();
    }).catch(e=>{
      message.error(e.response.data.message);
    });
  };

  getList(isFirst = false){
    const { page, size, searchParams, billingType, pagination } = this.state;
    searchParams.page = page;
    searchParams.size = size;
    searchParams.vendor = billingType;
    if(messages('common.all') === searchParams.title) {
      searchParams.title = '';
    }
    if(isFirst){
      searchParams.startDate = moment().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss');
      searchParams.endDate = moment().format('YYYY-MM-DD HH:mm:ss');
    }
    this.setState({ loading: true }, () => {
      waitForBillingService.getBillingList(searchParams).then(res => {
        res.data.map((item ,index) => {
          item.index = index + size * page + 1;
          item.currency = 'CNY';
          return item;
        });
        pagination.total = Number(res.headers['x-total-count']);
        pagination.onChange = this.onChangePager;
        pagination.current = page + 1;
        this.setState({
          loading: false,
          data: res.data,
          pagination
        })
      }).catch(e => {
        this.setState({loading: false});
        message.error(e.response.data.message);
      });
    });
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.size)
      this.setState({
        page: 0,
        size: size
      },() => {
        this.getList()
      })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  handleDetail = (e, record) => {
    e.stopPropagation();
    const { searchParams, page } = this.state;
    let cacheSearch = JSON.parse(JSON.stringify(searchParams));
    searchParams.title === '' && (cacheSearch.title = messages('common.all'));
    cacheSearch.page = page;
    configureStore.store.dispatch(setBillList(cacheSearch));
    this.props.dispatch(setBillingTab('done'));
    this.context.router.push(this.menuBillingDetail.url.replace(':receiptedInvoiceOID',record.receiptedInvoiceOID).replace(':billingType',this.state.billingType))
  };

  handleSearch = (result)=>{
    result.startDate ? (result.startDate = moment(result.startDate).format('YYYY-MM-DD 00:00:00')) : delete result.startDate;
    result.endDate ? (result.endDate = moment(result.endDate).format('YYYY-MM-DD 23:59:59')) : delete result.endDate;
    result.title = result.title ? result.title : '';
    this.setState({
      searchParams: result,
      page: 0
    }, ()=>{
      this.getList();
    })
  };

  clear = () => {
    const { searchForm } = this.state;
    searchForm[0].items.map(item => {
      item.defaultValue = null;
    });
    searchForm[1].defaultValue = null;
    this.setState({
      searchForm,
      searchParams: {}
    }, () => {
      const { searchParams } = this.state;
      let cacheSearch = JSON.parse(JSON.stringify(searchParams));
      cacheSearch.page = 0;
      configureStore.store.dispatch(setBillList(cacheSearch));
      this.getList();
    })
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType){
      case 'DIDI':
        result = messages('financial-management.key536'/*新建滴滴开票*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key555'/*新建甄汇酒店开票*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key556'/*新建神州开票*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };

  render(){
    const {  data, pagination, columns, loading ,buttonRoleSwitch, searchForm, searchParams } = this.state;
    return (
      <div className="wait-for-billing-list">
        <SearchArea searchForm={searchForm}
                    submitHandle={this.handleSearch}
                    clearHandle={this.clear}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <If value={buttonRoleSwitch && this.checkNewAuth()}>
            <div className="table-header-buttons">
              <ExportModal type={"btn"}
                           style={{
                             display: 'inline-block'
                           }}
                           exportTitle={messages('financial-management.key146')/*导出搜索数据*/}
                           exportType="DIDI_RECEIPTED_INVOICE"
                           exportCondition={{
                             vendor: searchParams.vendor,
                             companyOID: this.props.company.companyOID,
                             title: searchParams.title ? searchParams.title : null,
                             billCheckSearchCommand: {
                               beginDate: searchParams.startDate ? moment(searchParams.startDate).format('YYYY-MM-DD 00:00:00') : null,
                               endDate: searchParams.endDate ? moment(searchParams.endDate).format('YYYY-MM-DD 23:59:59') : null
                             }
                           }}
                           exportCommand={''}/>
            </div>
          </If>
        </div>
        <ResizeTable
          columns={columns}
          bordered
          pagination={pagination}
          loading={loading}
          rowKey="receiptedInvoiceOID"
          dataSource={data}
          size="middle"
          onRow={record => ({onClick: (e) => this.handleDetail(e,record)})}
        />
      </div>
    )
  }
}

WaitForBillingList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    profile: state.login.profile,
    user: state.login.user,
    billList: state.cache.billList,
  }
}

const wrappedWaitForBilling = Form.create()(WaitForBillingList);
export default connect(mapStateToProps)(wrappedWaitForBilling);
